
(function (){
  let SYS_NAME = "keywork_click";
  let search_id = SYS_NAME + "-search-engine-tools-box";

  function $(s) {
    return document.querySelector(s)
  }

  if($(`#${search_id}`) != null) return;



  // 注入兽兽搜索框元素
  let stebEl = document.createElement('div');
  stebEl.id = search_id;
  stebEl.classList.add("setools-search-el")
  stebEl.innerHTML = `<div class="search-box setools-search-el"><input class="setools-search-el" type="text"></div>`;
  document.body.appendChild(stebEl)

  // 页面上所有btn按钮
  let pageAllBtnEl = null;
  // 当前匹配的元素
  let curMatchElArr = [];
  // curMatchElArr 当前选择的索引
  let selectMatchElIndex = 0;

  /*
  * 更新当前匹配的元素样式
  * @type: string("remove", "add")
  */
  function updateMatchElStyle(type) {
    if(type == "remove") {
      curMatchElArr.forEach(el => {
        el.classList.remove(`${search_id}-match`);
        el.classList.remove(`${search_id}-highlight`);
      })
    }

    if(type == "add") {
      curMatchElArr.forEach((el, index) => {
        el.classList.add(`${search_id}-${(index == selectMatchElIndex? "highlight" : "match")}`);
      })
    }
  }

  /*
  * 跟据关键字搜索页面上按钮高亮显示
  * @type: 1 取消， 2 匹配
  * @keywork: string 关键字
  * @index: number 索引（选择第几个）
  */
  function match(type, keywork=new Date().getTime(), index=0) {
    // 不管是匹配还是取消先把样式还原
    restart()

    if(type != 2) return;

    // 获取元素
    if(pageAllBtnEl === null) {
      let temp_pageAllBtnEl = document.querySelectorAll('a,button');
      if(temp_pageAllBtnEl != null) {
        pageAllBtnEl = [];
        temp_pageAllBtnEl.forEach(el => {
          if(el.children.length == 0) pageAllBtnEl.push(el)
        })
      }
    }

    if(pageAllBtnEl != null) {
      pageAllBtnEl.forEach(el => {
        if(el.innerHTML.indexOf(keywork) != -1) {
          curMatchElArr.push(el)
        }
      })
    }

    // 添加匹配样式和选中样式
    updateMatchElStyle("add");
  }

  /*
  * 选择上一个或者下一个当前匹配的元素
  * @type: string('up', 'next')
  */
  function upOrNextMatchEl(type) {
    updateMatchElStyle("remove");
    if(type == 'up' && selectMatchElIndex != 0) selectMatchElIndex--;
    if(type == 'next' && selectMatchElIndex != curMatchElArr.length - 1) selectMatchElIndex++;
    updateMatchElStyle("add");
  }

  // 点击非兽兽搜素框以外的内容隐藏兽兽搜素
  window.addEventListener('click', function (e) {
    if (!e.target.classList.contains("setools-search-el")) {
      $(`#${search_id}`).classList.remove('show')

      restart();
    }
  })
  
function restart() {
  updateMatchElStyle("remove");
  curMatchElArr = [];
  selectMatchElIndex = 0;
}

  // 兽兽搜素输入框值发生改变
  $(`#${search_id} .search-box input`).addEventListener('input', function (e) {
    // ...
    match(2, e.target.value)
  })
  
  // 获取显示兽兽搜索框快捷键配置
  chrome.storage.sync.get("shortcutKey", function({shortcutKey}) {
    window.addEventListener('keydown', function(e) {
      let flag = true;
      shortcutKey.funKey.forEach(item => {
        if(!e[item]) flag = false;
      })
      if(e.keyCode != shortcutKey.ordinaryKeyCode) flag = false;
      // 显示兽兽搜索
      if(flag) {
        $(`#${search_id}`).classList.toggle('show')
        // 快捷键会触发一次input值改变
        setTimeout(() => {
          $(`#${search_id} .search-box input`).value = ""
          // 首次显示所有匹配元素
          match(2, '')
        }, 0);
        $(`#${search_id} .search-box input`).focus();
      }
    })
  })

  $(`#${search_id} .search-box input`).addEventListener('keydown', function(e) {  
    // 搜索框按下回车
    if(e.keyCode == 13 && this.value != "") {
      if(curMatchElArr[selectMatchElIndex]) curMatchElArr[selectMatchElIndex].click();
      restart();
    }
    
    // 按上下键 38=上
    if(e.keyCode == 38 || e.keyCode == 40) {
      upOrNextMatchEl(e.keyCode==38? "up" : "next");
      if(e.keyCode == 38) {
        setTimeout(() => {
          e.target.setSelectionRange(e.target.value.length, e.target.value.length)
        }, 0)
      }
    }
  })
})()